from odoo import fields, models, api, _
from odoo.exceptions import UserError


class MrpProductionBatchSubcontractingWizard(models.TransientModel):
    _name = 's.mrp.production.batch.subcontracting.wizard'
    _description = 'Batch subcontracting'

    workcenter_id = fields.Many2one('mrp.workcenter', 'subcontracting work', required=True)
    line_ids = fields.One2many('s.mrp.production.batch.subcontracting.line.wizard', 'order_id')
    area_calculation_method = fields.Selection([
        ('pnl', 'PNL'),
        ('set', 'SET')
    ], string='Area calculation method', default='pnl', required=True)

    def default_get(self, fields_list):
        result = super().default_get(fields_list)
        active_model = self._context.get('active_model', '')
        line_ids_vals = []
        if active_model == 'mrp.production':
            active_ids = self._context.get('active_ids', [])
            production_ids = self.env['mrp.production'].browse(active_ids).filtered(lambda x: x.state not in ('done', 'cancel'))
            for rec in production_ids:
                line_ids_vals.append((0, 0, {
                    'product_id': rec.product_id.id,
                    'production_id': rec.id,
                    'qty_wip': sum(rec.workorder_ids.mapped('qty_wip')),
                    'qty_wip_set': sum(rec.workorder_ids.mapped('qty_wip_set')),
                    'qty_wip_pnl': sum(rec.workorder_ids.mapped('qty_wip_pnl'))
                }))
        result['line_ids'] = line_ids_vals

        return result

    @api.onchange('area_calculation_method')
    def onchange_area_calculation_method(self):
        self.line_ids.write({'area_calculation_method': self.area_calculation_method})

    def button_confirm(self):
        self.ensure_one()
        line_vals_list = []
        for line in self.line_ids:
            workorder_ids = line.production_id.workorder_ids.filtered(lambda x: x.workcenter_id == self.workcenter_id)
            if not workorder_ids:
                raise UserError(_('%s, There is no material %s', line.production_id.name, self.workcenter_id.name))
            workorder_id = workorder_ids[0]
            if workorder_id.state == 'done':
                raise UserError(_('%s, %s, is done', line.production_id.name, self.workcenter_id.name))
            workorder_id.is_subcontracting = True
            line_vals_list.append((0, 0, {
                'production_id': line.production_id.id,
                'product_id': line.product_id.id,
                'workorder_id': workorder_id.id,
                'area_calculation_method': line.area_calculation_method
            }))
        if line_vals_list:
            apply_ids = self.env['sb.subcontracting.apply'].create({
                'line_ids': line_vals_list
            })
            for apply_line in apply_ids.mapped('line_ids'):
                apply_line.onchange_qty()
            action = self.env["ir.actions.act_window"]._for_xml_id('sb_subcontracting.sb_subcontracting_apply_act_window')
            action['domain'] = [('id', 'in', apply_ids.ids)]
            action['view_mode'] = 'form'
            return action


class MrpProductionBatchSubcontractingLineWizard(models.TransientModel):
    _name = 's.mrp.production.batch.subcontracting.line.wizard'
    _description = 'Batch subcontracting line'

    order_id = fields.Many2one('s.mrp.production.batch.subcontracting.wizard')
    production_id = fields.Many2one('mrp.production', string='Production')
    product_id = fields.Many2one('product.product', 'Product')
    qty_wip = fields.Float('Work In Process', digits='Product Unit of Measure')
    qty_wip_set = fields.Float('Work In Process (SET)', digits='Product Unit of Measure')
    qty_wip_pnl = fields.Float('Work In Process (PNL)', digits='Product Unit of Measure')

    outgoing_qty = fields.Integer('outgoing qty')

    area_calculation_method = fields.Selection([
        ('pnl', 'PNL'),
        ('set', 'SET')
    ], string='Area calculation method', default='pnl')


